import contextlib
import random
import time

from functools import wraps

from utils import connect


# 参数化的装饰器（可以通过传参定制你的装饰器）
def record_time(write_log):

    # 装饰器：传入被装饰的函数，返回带装饰功能的函数 ---> 代理模式
    def decorator(func):

        @wraps(func)
        def wrapper(*args, **kwargs):
            start = time.time()
            result = func(*args, **kwargs)
            end = time.time()
            write_log(func.__name__, end - start)
            return result

        return wrapper

    return decorator


def log_to_console(fname, duration):
    print(f'{fname}函数执行了{duration:.3f}秒')


def log_to_file(fname, duration):
    with open('mydata.log', 'a') as file:
        file.write(f'{fname}函数执行了{duration:.3f}秒\r\n')


def log_to_db(fname, duration):
    conn = connect(database='hrs')
    try:
        with conn.cursor() as cursor:
            cursor.execute(
                'insert into tb_log values (default, %s, %s)',
                (fname, duration)
            )
        conn.commit()
    finally:
        conn.close()


@record_time(log_to_db)
def download(filename):
    print(f'开始下载{filename}')
    time.sleep(random.randint(3, 8))
    print(f'{filename}函数下载完成')


# @record_time(log_to_console)
def fac(num):
    if num == 0:
        return 1
    return num * fac(num - 1)


@contextlib.contextmanager
def display_execution_time(fname, write_log):
    start = time.time()
    yield 'hello'
    end = time.time()
    write_log(fname, end - start)


with display_execution_time(fac.__name__, log_to_file) as message:
    print(message)
    result = fac(10)
print(result)


# # download = record_time(download)
# print(download.__name__)
# download('Python从入门到住院.avi')
# # 还原成原始的download函数（取消装饰器）
# download = download.__wrapped__
# download('东京有点热.avi')
